<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="2">
        <span style="color: blue">{{ tplItem.名称 }}</span>
      </el-col>
      <!-- <el-col :span="3">
        <el-switch
          @change="filterTable"
          v-model="hideBasicObj"
          :active-value="true"
          :inactive-value="false"
          active-text=""
          inactive-text="隐藏基础项目"
        >
        </el-switch>
      </el-col> -->
      <!-- <el-col :span="3">
        <el-switch
          @change="filterTable"
          v-model="隐藏备选项目"
          active-text=""
          inactive-text="隐藏备选项目"
        >
        </el-switch>
      </el-col> -->
      <el-col :span="3">
        <el-switch
          v-model="tplItem.是否审核"
          active-text="审核"
          inactive-text="取消审核"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-col>

      <el-col :span="2">
        <el-link type="primary" @click="查看文件('路径表单')">路径表单</el-link>
      </el-col>
      <el-col :span="2">
        <el-link type="primary" @click="查看文件('路径方案')">路径方案</el-link>
      </el-col>
      <!-- <el-col :span="1">
                          <el-button
                            type="success"
                            @click="查看文件('路径方案')"
                            style="margin-left: 5px"
                            round
                            >路径表单</el-button
                          >
                        </el-col> -->
      <el-col :span="4">
        <el-input
          v-model="s"
          @keyup.enter.native="filterTable"
          @input="
            (e) => {
              if (!e) {
                this.filterTable('');
              }
            }
          "
          style="margin-top: -5px"
          placeholder="类别、项目名称  回车"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-button
          round
          type="primary"
          @click="saveTpl"
          :loading="saveLoading"
          style="margin-top: -10px"
          >保存
        </el-button>
        <el-button round @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <el-row>
      <vxe-table
        border
        ref="myTable"
        :data="tplDataLs"
        :footer-method="summary"
        :loading="tplLoading"
        :show-footer="true"
        style="width: 100%"
        max-height="600"
        :row-style="rowStyle"
        show-overflow
        :row-config="{ isHover: true }"
      >
        <vxe-column fixed="left" type="seq" width="50"> </vxe-column>
        <vxe-column fixed="left" field="类别" title="类别" width="100">
          <template #header>
            <el-select
              v-model="typeValue"
              @change="changeOption('类别', $event)"
              clearable
              placeholder="请选择类别"
            >
              <el-option
                v-for="(item, index) in typeOption"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </template>
        </vxe-column>
        <vxe-column
          fixed="left"
          field="项目名称"
          :filters="[{ data: '' }]"
          :filter-method="filterRoleMethod"
          width="260"
          title="项目名称"
        >
          <template slot-scope="scope">
            <el-select
              @dblclick.native="dbclickName(scope.row, scope.$rowIndex, scope)"
              @focus="项目名称_focus(scope.row, $event)"
              @change="项目名称_change(scope.row, scope.row.项目名称)"
              v-model="scope.row.项目名称"
              filterable
              remote
              reserve-keyword
              ref="xTable"
              style="width: 90%"
              placeholder="请输入关键词"
              :remote-method="远程搜索项目"
              :loading="项目Loading"
              :disabled="tplItem.是否审核"
            >
              <el-option
                v-for="item in 匹配项目s"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              >
                <div class="drgItem">
                  <span>{{ item.label }}</span>
                  <span>{{ item.value.规格 }}</span>
                  <span style="color: #8492a6; font-size: 13px">{{
                    item.value.生产厂家
                  }}</span>
                </div>
              </el-option>
            </el-select>
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content" v-html="item_content(scope.row)"></div>

              <img
                style="width: 20px; height: 20px"
                class="pic-404__parent"
                src="@/assets/shuoming.png"
              />
            </el-tooltip>
          </template>
        </vxe-column>
        <!-- <vxe-column field="特征" title="特征" width="80">
          <template slot-scope="scope">
            <el-checkbox
              @click.native="isCritical(scope.row)"
              v-model="scope.row.是否关键"
            ></el-checkbox>
          </template>
        </vxe-column> -->
        <vxe-column field="单价" title="单价" width="100">
          <template slot-scope="scope">
            <template v-if="!tplItem.是否审核">
              <el-input
                v-if="scope.row.缺省"
                @change="updateFooterEvent"
                v-model="scope.row.单价"
                placeholder="单价"
              ></el-input>
              <span v-else>{{ scope.row.单价 }}</span>
            </template>

            <span v-else>{{ scope.row.单价 }}</span>
          </template>
        </vxe-column>
        <vxe-column field="数量" title="数量" width="100">
          <template slot-scope="scope">
            <template v-if="!tplItem.是否审核">
              <el-input
                v-if="scope.row.缺省"
                v-model="scope.row.数量"
                placeholder="数量"
                @change="updateFooterEvent"
              ></el-input>
              <span v-else>{{ scope.row.数量 }}</span>
            </template>
            <span v-else>{{ scope.row.数量 }}</span>
          </template>
        </vxe-column>

        <vxe-column field="金额" title="金额" width="80">
          <template #default="{ row }">
            <span>{{ 计算费用fmt(row) }} </span>
          </template>
        </vxe-column>

        <vxe-column field="项目属性" title="项目属性" width="120">
          <template #header>
            <el-select
              @change="changeOption('项目属性', $event)"
              clearable
              v-model="attributeValue"
              placeholder="请选择属性"
            >
              <el-option
                v-for="(item, index) in attributeOption"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="选择属性" title="选择属性" width="120">
          <template slot-scope="scope">
            <template v-if="!tplItem.是否审核">
              <el-select v-model="scope.row.选择属性" placeholder="请选择">
                <el-option
                  v-for="item in 选择属性s"
                  :key="item.value"
                  :label="item.lable"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>

            <span v-else>{{ scope.row.选择属性 }}</span>
          </template>
        </vxe-column>

        <vxe-column field="缺省" title="缺省" width="80">
          <template slot-scope="scope">
            <el-checkbox
              :disabled="tplItem.是否审核"
              @click.native="缺省_click(scope.row)"
              v-model="scope.row.缺省"
            ></el-checkbox>
          </template>
        </vxe-column>

        <vxe-column field="组号" title="组号" width="100">
          <template slot-scope="scope">
            <template v-if="!tplItem.是否审核">
              <el-select v-model="scope.row.组号" placeholder="请选择">
                <el-option
                  v-for="item in [
                    {
                      label: '',
                    },
                    {
                      label: 'I',
                    },
                    {
                      label: 'II',
                    },
                    {
                      label: 'III',
                    },
                    {
                      label: 'IV',
                    },
                    {
                      label: 'V',
                    },
                  ]"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </template>
            <span v-else>{{ scope.row.组号 }}</span>
          </template>
        </vxe-column>

        <vxe-column field="限制" title="限制" width="80">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.限制说明"
              Left="提示文字"
              placement="top-start"
            >
              <span style="color: red">{{ scope.row.限制 }}</span>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="模板费用" :title="'模板费用'" width="100">
          <template #default="{ row }">
            <span>{{ 费用结构情况fmt(row) }} </span>
          </template>
        </vxe-column>
        <vxe-column field="模板费用占比" :title="'模板费用\n占比%'" width="80">
          <template #default="{ row }">
            <span>{{ 模板费用占比fmt(row, "模板费用占比") }} </span>
          </template>
        </vxe-column>

        <vxe-column fixed="right" title="" width="100">
          <template slot-scope="scope" v-if="!tplItem.是否审核">
            <el-dropdown>
              <span class="el-dropdown-link" style="color: blue">
                操作<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  @click.native.prevent="
                    dropdown_itemClick(scope.row, scope.rowIndex, 'insertUP')
                  "
                  icon="el-icon-plus"
                  >添加（上）</el-dropdown-item
                >
                <el-dropdown-item
                  @click.native.prevent="
                    dropdown_itemClick(scope.row, scope.rowIndex, 'insertDown')
                  "
                  icon="el-icon-plus"
                  >添加（下）</el-dropdown-item
                >

                <el-dropdown-item
                  @click.native.prevent="
                    dropdownInsertType_itemClick(
                      scope.row,
                      scope.rowIndex,
                      'insertTypeUP'
                    )
                  "
                  icon="el-icon-plus"
                  >插入类别（上）</el-dropdown-item
                >
                <el-dropdown-item
                  @click.native.prevent="
                    dropdownInsertType_itemClick(
                      scope.row,
                      scope.rowIndex,
                      'insertTypeDown'
                    )
                  "
                  icon="el-icon-plus"
                  >插入类别（下）</el-dropdown-item
                >

                <el-dropdown-item
                  @click.native.prevent="
                    dropdown_itemClick(scope.row, scope.rowIndex, 'remove')
                  "
                  icon="el-icon-close"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </vxe-column>
      </vxe-table>
    </el-row>
    <el-row>
      <el-descriptions title="模板类型">
        <el-descriptions-item label="路径版本">
          {{ tplItem.路径版本 }}
        </el-descriptions-item>
        <el-descriptions-item label="当前分组">
          <el-select
            style="width: 180px"
            @change="tplitem_change"
            v-model="tplItem.分组编码"
            placeholder="请选择"
          >
            <el-option
              v-for="item in drgNameLs"
              :key="item.分组编码"
              :label="item.分组编码 + '-' + item.分组名称"
              :value="item.分组编码"
            >
            </el-option>
          </el-select>
        </el-descriptions-item>

        <!-- <el-descriptions-item label="时间段内当前模版的本院数据">
                                      {{ 模板病例数 }}
                                  </el-descriptions-item> -->
      </el-descriptions>
    </el-row>

    <el-row>
      <el-descriptions title="大数据标杆">
        <el-descriptions-item label="医保付费标杆">
          {{ 大数据标杆.平均费用 }}
        </el-descriptions-item>
        <el-descriptions-item label="药品费">
          {{ 大数据标杆.平均药品费 }}
        </el-descriptions-item>
        <el-descriptions-item label="检验费">
          {{ 大数据标杆.平均检验费 }}
        </el-descriptions-item>
        <el-descriptions-item label="检查费">
          {{ 大数据标杆.平均检查费 }}
        </el-descriptions-item>
        <el-descriptions-item label="治疗费">
          {{ 大数据标杆.平均治疗费 }}
        </el-descriptions-item>
        <el-descriptions-item label="手术费">
          {{ 大数据标杆.平均手术费 }}
        </el-descriptions-item>
        <el-descriptions-item label="耗材费">
          {{ 大数据标杆.平均耗材费 }}
        </el-descriptions-item>
        <el-descriptions-item label="医保床日标杆">
          {{ 历史标杆.平均床日 }}
        </el-descriptions-item>
      </el-descriptions>
    </el-row>

    <el-row>
      <el-descriptions title="本院历史标杆">
        <el-descriptions-item label="本院次均费用">
          {{ 历史标杆.平均费用 }}
        </el-descriptions-item>
        <el-descriptions-item
          :label="是否中医性质 ? '（西药）成药费' : '药品费'"
        >
          {{ 历史标杆.平均药品费 }}
        </el-descriptions-item>
        <el-descriptions-item label="检验费">
          {{ 历史标杆.平均检验费 }}
        </el-descriptions-item>
        <el-descriptions-item label="检查费">
          {{ 历史标杆.平均检查费 }}
        </el-descriptions-item>
        <el-descriptions-item label="治疗费">
          {{ 历史标杆.平均治疗费 }}
        </el-descriptions-item>
        <el-descriptions-item label="手术费">
          {{ 历史标杆.平均手术费 }}
        </el-descriptions-item>
        <el-descriptions-item label="耗材费">
          {{ 历史标杆.平均耗材费 }}
        </el-descriptions-item>
        <el-descriptions-item label="本院平均床日">
          {{ 大数据标杆.平均床日 }}
        </el-descriptions-item>
        <el-descriptions-item v-if="是否中医性质" label="草药费">
          {{ 历史标杆.平均草药费 }}
        </el-descriptions-item>
      </el-descriptions>
    </el-row>

    <el-row>
      <el-dialog
        :title="uploadTitle"
        :visible.sync="uploadDialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <ul class="el-upload-list el-upload-list--text">
          <li
            v-for="f in 文件s"
            v-bind:key="f.name"
            class="el-upload-list__item is-ready"
          >
            <a
              class="el-upload-list__item-name"
              target="_blank"
              :href="downLoadUrl + '/' + f.url"
              ><i class="el-icon-document"></i>{{ f.name }}</a
            >
          </li>
        </ul>
      </el-dialog>
    </el-row>
    <el-dialog
      title="病种关联项目选择"
      :visible.sync="isOpenVisible"
      :before-close="itemSelectClose"
      width="1200px"
    >
      <!-- 筛选条件 -->
      <div class="dilog-filter">
        <!-- <el-select
          style="width: 360px"
          v-model="searchValue"
          filterable
          remote
          :remote-method="remoteMethod"
          placeholder="请选择"
          @change="serchDialogList"
        >
          <el-option
            v-for="item in searchOption"
            :key="item.id"
            :label="item.mc"
            :value="item.id"
          >
          </el-option>
        </el-select> -->
        <div class="set-more">
          <span>
            选择属性
            <el-select
              @change="changeAllAttr('选择属性', $event)"
              style="width: 150px"
              v-model="attrVal"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in 选择属性s"
                :key="item.value"
                :label="item.lable"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </span>
          <span class="flex-between">
            缺省
            <el-checkbox
              @change="changeAllAttr('缺省', $event)"
              v-model="isDefault"
            ></el-checkbox>
          </span>
          <span>
            组号
            <el-select
              @change="changeAllAttr('组号', $event)"
              v-model="groupCode"
              placeholder="请选择"
            >
              <el-option
                v-for="item in [
                  {
                    label: '',
                  },
                  {
                    label: 'I',
                  },
                  {
                    label: 'II',
                  },
                  {
                    label: 'III',
                  },
                  {
                    label: 'IV',
                  },
                  {
                    label: 'V',
                  },
                ]"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </span>
          <span>
            数量
            <el-input
              @change="changeAllAttr('数量', $event)"
              style="width: 150px"
              placeholder="请输入"
              v-model="numInp"
            ></el-input>
          </span>
        </div>
      </div>
      <!-- 表格 -->
      <el-table
        :data="dialogTableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        >>
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="index" label="序号" width="100">
        </el-table-column>
        <el-table-column prop="类别" label="收费类别"> </el-table-column>
        <el-table-column prop="项目名称" label="收费项目名称" width="180">
        </el-table-column>
        <el-table-column prop="数量" label="数量">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.数量"
              placeholder="数量"
              @change="updateFooterEvent"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="单价" label="单价">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.单价"
              placeholder="单价"
              @change="updateFooterEvent"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="金额" label="金额">
          <template slot-scope="{ row }">
            <span>{{ 计算费用fmt(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="项目属性" label="项目属性"> </el-table-column>
        <el-table-column prop="选择属性" label="选择属性" width="120">
          <template slot-scope="{ row }">
            <el-select v-model="row.选择属性" filterable placeholder="请选择">
              <el-option
                v-for="item in 选择属性s"
                :key="item.value"
                :label="item.lable"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="缺省" label="缺省">
          <template slot-scope="{ row }">
            <el-checkbox v-model="row.缺省"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="组号" label="组号" width="120">
          <template slot-scope="{ row }">
            <el-select v-model="row.组号" placeholder="请选择">
              <el-option
                v-for="item in [
                  {
                    label: '',
                  },
                  {
                    label: 'I',
                  },
                  {
                    label: 'II',
                  },
                  {
                    label: 'III',
                  },
                  {
                    label: 'IV',
                  },
                  {
                    label: 'V',
                  },
                ]"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="限制" label="限制"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="confirmDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, ModelSync, Vue } from "vue-property-decorator";
import {
  tplDetail,
  saveTpl,
  drgNames,
  drgInfo,
  cnHops,
  saveTplDrg,
  drgweightbyid,
  searchListInKey,
  searchListInVal,
} from "@/api/PathTemplate";
import { GetTplById } from "@/api/pathway";
import { Format } from "@/utils/Utils";
import { autoName } from "@/api/commonApi";
import { LsFiles, DestoryFile } from "@/api/commonApi";
import { UserModule } from "@/store/modules/user";
import table2excel from "@/utils/exccel";
@Component({
  name: "tpledit",
})
export default class extends Vue {
  public multipleSelection: any = [];
  public rowIndex: number = 0;
  public isOpenVisible: Boolean = false;
  public typeValue: String = "类别";
  public typeOption: Array<any> = [];
  public attributeValue: String = "项目属性";
  public attributeOption: Array<any> = [];
  public filterQuery: Array<any> = [];

  public searchValue: string = "";
  public searchOption: Array<any> = [];
  public dialogTableData: Array<any> = [];
  private tplid: string = "";

  public 项目Loading: boolean = false;

  public 匹配项目s: Array<any> = [];

  private uploadDialogVisible: boolean = false;
  private uploadTitle: string = "";
  private 文件s: Array<any> = [];
  private downLoadUrl = `${(<any>window).MyConf.APISERVICE}/files/`;

  private myTable: any = this.$refs.myTable;
  private itemSelectClose() {
    this.isOpenVisible = false;
    this.initDialogData();
  }
  private handleSelectionChange(e: any) {
    this.multipleSelection = e;
  }
  private updateFooterEvent() {
    let xTable: any = this.$refs.myTable;
    xTable.updateFooter();
  }
  private rowStyle(p: any) {
    let row = p.row;
    let sy: any = {};
    if (row.特征对比结果) {
      sy.color = "red";
    }
    if (row.hidden) {
      sy.visibility = "hidden";
    }
    return sy;
  }
  private async 查看文件(t: string) {
    let ts = [];
    this.uploadDialogVisible = true;
    this.uploadTitle = t;

    const { data } = await LsFiles({ tpl: `${this.tplid}-${t}` });
    this.文件s = data;
  }

  private editRow: any = {};
  public isCritical(row: any) {
    row.是否关键 = !row.是否关键;
    this.updateFooterEvent();
  }
  public 缺省_click(row: any) {
    if (row.缺省) {
      row.数量 = null;
    }
    this.updateFooterEvent();
  }
  public 项目名称_focus(row: any, $event: any) {
    this.editRow = row;
  }
  public item_content(row: any) {
    return `${row.项目名称}<br/> ${row.产地 || ""}&nbsp;&nbsp;${
      row.规格 || ""
    }<br/>${row.适用范围}`;
  }

  public 项目名称_change(row: any, value: any) {
    row.项目id = value.项目id;
    row.项目名称 = value.名称;
    row.项目属性 = "";

    row.产地 = value.生产厂家;
    row.规格 = value.规格;
    if (value.售价) {
      row.单价 = value.售价;
    }

    if (value.属性 == 1) row.项目属性 = "基础项目";
    if (value.属性 == 2) row.项目属性 = "不判断";

    //项目重复检查
    setTimeout(() => {
      let ts = this.重复检查();
      if (ts.length > 0) {
        this.$message({
          message: `${ts.join("、")} 重复！`,
          type: "error",
          center: true,
          duration: 2 * 1000,
        });
      }
    }, 50);
  }
  private 重复检查() {
    // if (项目名称) {
    //     if (this.tplDataLs.filter((it: any) => `${it.项目名称}${it.规格}${it.产地}`==项目名称).length > 1) {
    //         return [项目名称];
    //     }
    // }
    let ts = this.tplDataLs.map((it: any) => ({
      项目名称: it.项目名称,
      k: `${it.项目名称}${it.规格}${it.产地}`,
    }));
    let o: any = {};
    let ts2: Array<any> = [];

    ts.forEach((it: any) => {
      if (o[it.k] && o[it.k] == 1) {
        ts2.push(it.项目名称);
      }
      o[it.k] = (o[it.k] || 0) + 1;
    });

    return ts2;
  }
  public async 远程搜索项目(query: any) {
    this.项目Loading = true;
    const { data } = await autoName({ proType: this.editRow.类别, s: query });
    this.匹配项目s =
      data.map((it: any) => ({
        id: it.ID,
        label: it.名称,
        value: it,
        data: it,
      })) || [];
    this.项目Loading = false;
  }

  //隐藏基础项目
  public hideBasicObj: boolean = false;
  public 隐藏备选项目: boolean = false;
  public 本市标杆: boolean = false;
  public s: string = "";

  public filterTable($event: any) {
    let ts: any = this.tplDataLsCopy;
    if (this.hideBasicObj) {
      ts = ts.filter((it: any) => it.项目属性 !== "基础项目");
    }
    if (this.隐藏备选项目) {
      ts = ts.filter((it: any) => it.缺省);
    }

    ts = ts.filter(
      (it: any) =>
        it.类别.indexOf(this.s) > -1 || it.项目名称.indexOf(this.s) > -1
    );

    this.tplDataLs = ts;
    // this.searchLs = ts.length == 0 ? null : ts;

    // setTimeout(() => {
    //   // this.tplDataLs = JSON.parse(JSON.stringify(this.tplDataLs))
    //   // this.searchLs = JSON.parse(JSON.stringify(this.searchLs))
    //   let xTable: any = this.$refs.myTable;
    //   xTable.updateData();
    // }, 100);

    // let xTable: any = this.$refs.myTable;
    // xTable.updateData();
    //$table.updateData()
  }
  public 项目属性s = [
    {
      lable: "无",
      value: "",
    },
    {
      lable: "基础项目",
      value: "基础项目",
    },
    {
      lable: "不判断",
      value: "不判断",
    },
  ];
  public attrVal = null;
  public isDefault = false;
  public groupCode = "";
  public numInp = 0;
  public 选择属性s = [
    {
      lable: "可选",
      value: "",
    },
    {
      lable: "必选",
      value: "必选",
    },
  ];

  public 模板名称: string = "";
  private created() {
    this.tplid = <string>this.$route.query.tid;
    this.模板名称 = <string>this.$route.query.tn;
    this.中医性质();
    this.loadTplDetail(this.tplid);
    this.loadTplById(this.tplid);
  }

  /**
   * 插入类别
   * @param row
   * @param index
   * @param cmd
   */
  public dropdownInsertType_itemClick(row: any, index: number, cmd: string) {
    if (cmd.startsWith("insertType")) {
      this.$prompt("请输入类别", "输入框", {
        inputPlaceholder: "如：药品、检验、检查、治疗、手术、耗材等",
      }).then((p: any) => {
        if (p.value) {
          this.dropdown_itemClick(row, index, cmd, p.value);
        }
      });
    }
  }
  private handleClose() {
    this.uploadDialogVisible = false;
  }
  private filterRoleMethod() {}
  //双击打开弹窗
  private dbclickName(row, index, { seq }) {
    console.log(index, row, seq, "index---");
    //禁用状态不打开
    if (this.tplItem.是否审核) {
      return;
    }
    this.rowIndex = seq - 1;
    this.isOpenVisible = true;
    this.serchDialogList(row.类别, this.tplid);
  }
  private async remoteMethod(e) {
    try {
      const res = await searchListInKey({ key: e });
      this.searchOption = res.data;
    } catch (error) {}
  }
  private async serchDialogList(lb, zlid) {
    const res = await searchListInVal({ lb, zlid });
    const row = this.tplDataLs[this.rowIndex];
    const listData = res.data.map((v: any) => {
      return {
        类别: v.lb,
        缺省: false,
        模板费用: row.模板费用,
        标杆费用: row.标杆费用,
        本市标杆: row.本市标杆,
        本院标杆: row.本院标杆,
        模板费用占比: row.模板费用占比,
        费用结构情况: `${row.模板费用}/${
          this.本市标杆 ? row.本市标杆 : row.本院历史标杆
        }`,
        项目id: v.id,
        项目名称: v.mc,
        项目属性: "",
        单价: v.dj,
        项目编码: v.bm,
        数量: v.sl,
      };
    });
    this.dialogTableData = listData;
  }
  private changeAllAttr(key: any, value: any) {
    console.log(key, value, "key value-----");
    this.dialogTableData = this.dialogTableData.map((v: any) => {
      return {
        ...v,
        [key]: value,
      };
    });
  }
  private cancelDialog() {
    this.isOpenVisible = false;
    this.initDialogData();
  }
  private confirmDialog() {
    if (!this.multipleSelection.length) {
      return this.$message.warning("请勾选项目");
    }
    this.isOpenVisible = false;
    //插入主数据
    this.tplDataLs.splice(this.rowIndex + 1, 0, ...this.multipleSelection);
    this.initDialogData();
  }
  private initDialogData() {
    this.dialogTableData = [];
    this.multipleSelection = [];
    this.searchValue = "";
    this.attrVal = "";
    this.isDefault = false;
    this.groupCode = "";
    this.numInp = 0;
  }
  //改变选项筛选数据
  private changeOption(key, e) {
    if (e) {
      //如果存在相同的筛选条件先删除 再添加新的
      if (this.filterQuery.some((v) => v.key == key)) {
        this.filterQuery = this.filterQuery.filter((v) => v.key != key);
      }
      this.filterQuery.push({ key, value: e });
    } else {
      this.filterQuery = this.filterQuery.filter((v) => v.key != key);
    }
    //筛选数据
    console.log(this.filterQuery);

    let filterData = this.tplDataLsCopy;
    if (!this.filterQuery.length) {
      filterData = this.tplDataLsCopy;
    } else {
      filterData = this.filterQuery.reduce((pre, cur) => {
        const res = pre.filter((v) => v[cur.key] == cur.value);
        return res;
      }, this.tplDataLsCopy);
    }
    console.log(filterData, "结果----------");
    this.tplDataLs = filterData;
  }
  public dropdown_itemClick(
    row: any,
    index: number,
    cmd: string,
    catory: string = ""
  ) {
    if (cmd == "remove") {
      let index = this.tplDataLs.indexOf(row);
      this.tplDataLs.splice(index, 1);
      index = this.tplDataLsCopy.indexOf(row);
      this.tplDataLsCopy.splice(index, 1);
    }

    if (cmd.startsWith("insert")) {
      let i = 1;
      if (cmd.endsWith("UP")) i = 0;
      index = index + i;
      index = index < 0 ? 0 : index;
      let o = {
        类别: catory || row.类别,
        缺省: false,
        单价: null,
        数量: null,
        模板费用: row.模板费用,
        标杆费用: row.标杆费用,
        本市标杆: row.本市标杆,
        本院标杆: row.本院标杆,
        模板费用占比: row.模板费用占比,
        费用结构情况: `${row.模板费用}/${
          this.本市标杆 ? row.本市标杆 : row.本院标杆
        }`,
      };
      console.log("insert...", index);
      this.tplDataLs.splice(index, 0, o);
      //this.tplDataLsCopy.splice(index, 0, o);
    }
  }

  public summary(param: any) {
    const { columns, data } = param;
    // console.log(columns, data);
    // let sums: any = [];
    // columns.forEach((c: any, index: number) => {
    //   if (index == 0) sums[index] = "合计";
    //   else if (c.property == "模板费用") {
    //     let ts = data
    //       .filter((it: any) => it.单价 && it.数量)
    //       .map((it: any) => it.单价 * it.数量)
    //       .reduce((a: number, b: number) => a + b, 0);
    //     sums[index] = (ts || 0).toFixed(2);
    //   }
    // });
    // console.log(sums);
    let footerData = [
      columns.map((column: any, columnIndex: any) => {
        if (columnIndex === 1) {
          return "合计";
        }
        if (["模板费用"].includes(column.field)) {
          let ts = data
            .filter((it: any) => it.单价 && it.数量)
            .map((it: any) => it.单价 * it.数量)
            .reduce((a: number, b: number) => a + b, 0);
          return (ts || 0).toFixed(2);
        }
        if (["rate"].includes(column.field)) {
          return "不想换行不想换行不想换行不想换行不想换行不想换行不想换行不想换行";
        }
        return null;
      }),
    ];
    return footerData;
  }

  public 模板费用占比fmt(row: any, column: any) {
    let total = this.tplDataLs
      .filter((it: any) => it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);

    let r = this.tplDataLs
      .filter((it: any) => it.类别 == row.类别 && it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);

    let v = 0;
    if (total > 0) {
      v = (r / total) * 100;
    }
    row[column] = v;
    return v.toFixed(2);
  }

  public 费用结构情况fmt(row: any) {
    let 类别 = row.类别;
    let r = this.tplDataLs
      .filter((it: any) => it.类别 == 类别 && it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);
    row["模板费用"] = r;

    return r.toFixed(2);
  }

  public 计算费用fmt(row: any) {
    let c = "金额";

    let v = 0;
    if (row.数量 && row.单价) {
      v = row.数量 * row.单价;
    }
    row[c] = v;

    if (v == 0) return "";

    return v.toFixed(2);
  }
  public objectSpanMethod(r: any) {
    const { row, column, rowIndex, columnIndex } = r;

    let cols = ["类别", "费用结构情况", "模板费用占比"];

    if (!cols.includes(column.property)) {
      return {
        rowspan: 1,
        colspan: 1,
      };
    }

    if (!this.tplDataLs[rowIndex]) {
      // 1列 1行
      return {
        rowspan: 1,
        colspan: 1,
      };
    }

    if (this.tplDataLs[rowIndex - 1]) {
      if (
        this.tplDataLs[rowIndex][column.property] ==
        this.tplDataLs[rowIndex - 1][column.property]
      ) {
        // 0列 0 行
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
    if (this.tplDataLs[rowIndex + 1]) {
      if (
        this.tplDataLs[rowIndex][column.property] ==
        this.tplDataLs[rowIndex + 1][column.property]
      ) {
        let conutRowSpan = 1;
        let countIndex = 1;
        var len = this.tplDataLs.length;
        // 往下遍历 重复的列有几个 合并几个
        for (var i = rowIndex; i <= len; i++) {
          // 遍历数组
          if (
            this.tplDataLs[rowIndex + countIndex] &&
            this.tplDataLs[rowIndex][column.property] ==
              this.tplDataLs[rowIndex + countIndex][column.property]
          ) {
            countIndex += 1;
            conutRowSpan += 1;
          } else {
            break;
          }
        }
        // 2列1行
        return {
          rowspan: conutRowSpan,
          colspan: 1,
        };
      }
    }
  }

  //table数据源
  public tplDataLs: Array<any> = [];
  //数据源副本
  public tplDataLsCopy: Array<any> = [];

  public tplLoading: boolean = true;

  public saveLoading: boolean = false;

  /**
   * 保存模板TplDrg权重
   */
  private async saveTplDrg() {
    let o: any = JSON.parse(JSON.stringify(this.大数据标杆));

    let d: any = await drgweightbyid({
      wid: this.tplItem.路径ID,
      code: o.分组编码,
    });
    let ts = d.data || [];
    //模板标杆
    d = ts.filter((it: any) => it.来源 == 3);
    if (d.length > 0) {
      d = d[0];
      ts.filter((it: any) => it.来源 != 3).forEach((it: any) => {
        it.默认 = false;
        it.审核人 = "";
        it.审核时间 = "";
        saveTplDrg(it);
      });
    }

    let drgObj: any = {};
    this.tplDataLs.forEach((it: any) => {
      drgObj[it.类别] = it.模板费用;
    });
    o.mdc专业 = o.MDC专业;
    o.mdc中文名称 = o.MDC中文名称;
    o.路径id = this.tplItem.路径ID;
    Object.keys(drgObj).forEach((k: string) => {
      o[`平均${k}费`] = drgObj[k];
      d[`标准${k}费`] = drgObj[k];
    });
    // d.标准总费用 = o.平均费用;
    //  d.标准总费用 =
    // (Number(o.平均其他费) || 0) +
    // (Number(o.平均手术费) || 0) +
    // (Number(o.平均检查费) || 0) +
    // (Number(o.平均检验费) || 0) +
    // (Number(o.平均治疗费) || 0) +
    // (Number(o.平均耗材费) || 0) +
    // (Number(o.平均药品费) || 0) +
    // (Number(o.平均药品费) || 0) +
    // (Number(o.平均费用) || 0);
    const totalNum = this.tplDataLs
      .filter((it: any) => it.单价 && it.数量)
      .map((it: any) => it.单价 * it.数量)
      .reduce((a: number, b: number) => a + b, 0)
      .toFixed(2);
    d.标准总费用 = totalNum;
    d.标准床日 = o.平均床日;
    o.来源 = 3;
    d.默认 = true;
    d.审核人 = UserModule.name;
    d.审核时间 = new Date();
    o.来自模板 = true;
    console.log(
      o,
      totalNum,
      drgObj,
      "o数据---------------------------------------"
    );

    await saveTplDrg(d);
  }
  //保存模板
  public async saveTpl() {
    if (this.s) {
      return this.$message.warning("请清除筛选条件");
    }
    if (!this.tplDataLs.length) {
      return this.$message.error("数据为空");
    }
    //查询过程中的不允许保存
    if (
      (this.typeValue !== "类别" && this.typeValue !== "") ||
      (this.attributeValue !== "项目属性" && this.attributeValue !== "")
    ) {
      return this.$message.warning(
        "类别或项目属性筛选下不可保存，请清除后重试"
      );
    }
    console.log(this.typeValue, "----");

    this.saveLoading = true;
    let 选择属性Map: any = {
      "": 0,
      必选: 1,
      可选: 0,
    };
    let 路径ID: any = this.tplDataLs.filter((it: any) => !!it.路径ID);
    if (路径ID.length > 0) {
      路径ID = 路径ID[0].路径ID;
    } else 路径ID = 0;

    this.tplDataLs.forEach((it: any, index: number) => {
      it.版本ID = this.tplid;
      it.执行性质 = 选择属性Map[it.选择属性];
      it.路径ID = 路径ID;
      it.序号 = index + 1;
    });
    let ls = JSON.parse(JSON.stringify(this.tplDataLs));
    ls.forEach((it: any) => {
      if (it.单价) it.单价 = parseFloat(it.单价);
      it.模板分类费用占比 = it.模板费用占比;
      it.模板病例数 = this.模板病例数;
    });
    if (this.tplItem.是否审核) {
      this.tplItem.审核时间 = Format("yyyy-MM-dd hh:mm:ss", new Date());
    } else {
      this.tplItem.审核时间 = "";
    }
    let ts = this.重复检查();
    if (ts.length > 0) {
      this.$alert(`${ts.join("、")} 重复！`);
    }
    /**
         * 初始化要求：
        1）组号一样
        2）选择属性，同为必选，或者同为可选；

         */
    let ts3 = ls
      .map((it: any) => ({ 选择属性: it.选择属性 || "可选", 组号: it.组号 }))
      .filter((it: any) => it.组号)
      .map((it: any) => `${it.选择属性}_${it.组号}`);
    if (ts3.length > 0) {
      let oo: any = {};
      ts3.forEach((t: any) => {
        oo[t] = (oo[t] || 0) + 1;
      });
      if (Object.keys(oo).filter((k: string) => oo[k] == 1).length > 0) {
        this.$message("组号和选择属性必须统一！");
      }
    }
    this.tplItem.最近修改人 = UserModule.name;
    let o = { tpl: this.tplItem, ls: ls };
    let m = await saveTpl({ json: JSON.stringify(o) });

    if (this.tplItem.是否审核) this.saveTplDrg();
    this.saveLoading = false;
    this.$message("操作成功！");

    await this.loadTplById(this.tplid);
    if (this.tplDataLs.filter((it: any) => it.特征对比结果).length > 0) {
      //
      this.$message({
        type: "error",
        message: "红色项目可能不符合该路径，请详细检查！",
        duration: 5 * 1000,
      });
    }
  }

  public tplItem: any = {};
  private async loadTplById(tplid: string) {
    const { data } = await GetTplById({ id: tplid });
    this.tplItem = (data || {}).tpl;
    this.loadDrgNames(this.tplItem.路径ID);
  }

  public drgNameLs: Array<any> = [];

  private async loadDrgNames(wid: any) {
    const { data } = await drgNames({ wid: wid });
    this.drgNameLs = data || [];
    let ts = this.drgNameLs.filter(
      (it: any) => it.分组编码 == this.tplItem.分组编码
    );

    if (ts.length == 0 && this.drgNameLs.length > 0) {
      let t = this.tplItem.路径版本;
      if (t) {
        t = t.split("-")[0];
      }
      //先找5、9的
      let ts2 = this.drgNameLs.filter((it: any) => {
        return it.分组编码 == t + "5" || it.分组编码 == t + "9";
      });
      if (ts2.length == 0) {
        ts2 = this.drgNameLs.filter((it: any) => {
          return it.分组编码.startsWith(t);
        });
        if (ts2.length > 0) {
          this.tplItem.分组编码 = ts2[0].分组编码;
        } else {
          this.tplItem.分组编码 = this.drgNameLs[0].分组编码;
        }
      } else {
        this.tplItem.分组编码 = ts2[0].分组编码;
      }
    }
    this.loadDrgInfo(this.tplItem.分组编码);
  }

  private drgInfoes: Array<any> = [];
  private async loadDrgInfo(code: any) {
    const { data } = await drgInfo({ code: code });
    this.drgInfoes = data || [];
    this.大数据And历史标杆赋值();
  }

  private 大数据标杆: any = {};
  private 历史标杆: any = {};

  private 大数据And历史标杆赋值() {
    let ts = this.drgInfoes.filter((it: any) => it.版本 == "CHSDRG");
    if (ts.length > 0) {
      this.大数据标杆 = ts[0];
    }
    ts = this.drgInfoes.filter((it: any) => it.版本 == "HIS");
    if (ts.length > 0) {
      this.历史标杆 = ts[0];
    }
  }

  public tplitem_change(val: any) {
    this.loadDrgInfo(this.tplItem.分组编码);
    //this.大数据And历史标杆赋值();
  }
  private 是否中医性质: boolean = false;
  private async 中医性质() {
    const { data } = await cnHops({});
    this.是否中医性质 = data;
  }

  private handleExport() {
    var column = [];
    (this.$refs["myTable"] as any).$children.forEach((element) => {
      // console.log(element);

      if (element.title && element.title != "操作") {
        let temp = {
          title: element.title,
          key: element.field, //key值对应表单数据字段名称
          type: "text",
        };
        column.push(temp);
      }
    });
    const exportData = JSON.parse(JSON.stringify(this.tplDataLs)).map((v) => {
      return {
        ...v,
        单价: v.单价 || "",
        数量: v.数量 || "",
        金额: v.金额 || "",
        模板费用: v.模板费用 || "",
        组号: v.组号 || "",
        限制: v.限制 || "",
        缺省: v.缺省 ? "缺省" : "",
        模板费用占比: Number(v.模板费用占比).toFixed(2),
      };
    });
    console.log(exportData, "处理表格数据");

    table2excel(column, exportData, this.tplItem.名称); //生成Excel表格，自动下载
  }
  private 模板病例数: any = 0;

  private async loadTplDetail(tplid: string) {
    this.tplLoading = true;

    let d = await tplDetail({ tplid: tplid });
    let data = d.data || [];
    if (data.length == 0) {
      data = [];
    }
    let o: any = {};

    data.forEach((el: any, i: number) => {
      el.缺省 = el.数量 * el.单价 > 0.0;
      o[el.类别] = o[el.类别] || [];
      o[el.类别].push(el);
    });
    this.tplDataLs = data;
    this.tplDataLsCopy = JSON.parse(JSON.stringify(data));
    //赋值表头各选项列表
    this.typeOption = [
      ...new Set(data.filter((v) => v.类别).map((v) => v.类别)),
    ];
    this.attributeOption = [
      ...new Set(data.filter((v) => v.项目属性).map((v) => v.项目属性)),
    ];
    if (this.tplDataLs.length > 0) {
      this.模板病例数 = this.tplDataLs[0].模板病例数 || 0;
    }
    this.tplDataLsCopy = JSON.parse(JSON.stringify(this.tplDataLs));
    this.tplLoading = false;
  }
}
</script>

<style lang="scss">
.el-table .cell {
  white-space: pre-line !important;
}

.el-row {
  padding: 5px;
}

.drgItem span + span {
  margin-left: 5px;
}

.el-descriptions__title {
  color: blue;
}

.menuDiv {
  display: none;
  position: absolute;

  .menuUl {
    height: auto;
    width: auto;
    font-size: 14px;
    text-align: left;
    border-radius: 3px;
    border: none;
    background-color: #c4c4c4;
    color: #fff;
    list-style: none;
    padding: 0 10px;

    li {
      width: 140px;
      height: 35px;
      line-height: 35px;
      cursor: pointer;
      border-bottom: 1px solid rgba(255, 255, 255, 0.47);

      &:hover {
        // background-color: rgb(26, 117, 158);
        color: rgb(54, 138, 175);
      }
    }
  }
}
.dilog-filter {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .set-more {
    display: flex;
    span {
      margin-right: 10px;
    }
  }
}
.flex-between {
  display: flex;
  align-items: center;
}
</style>
